package web.PetStore.web.servlet;

import web.PetStore.domain.Account;
import web.PetStore.domain.Cart;
import web.PetStore.domain.Log;
import web.PetStore.domain.Product;
import web.PetStore.service.CartService;
import web.PetStore.service.LogService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet(name = "AddCartServlet",urlPatterns = {"/AddCart"})
public class AddCartServlet extends HttpServlet {
    private LogService logService = new LogService();
    private CartService cartService = new CartService();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        HttpSession session = req.getSession();
        Product product = (Product) session.getAttribute("showingProduct");
        Account loginUser = (Account) session.getAttribute("loginUser");

        //记录日志
        logService.newLog(new Log(loginUser.getUserid(), "将-" + product.getBreed() + "-宠物加入了购物车"));

        Cart cart = new Cart();
        cart.setProductid(product.getProductId());
        cart.setUserid(loginUser.getUserid());
        cart.setImageSrc(product.getImageSrc());
        cart.setImageSize("small");
        cart.setName(product.getSpecies() + "-" + product.getBreed());
        cart.setNum(1);
        cart.setUnitprice(product.getUnitprice());
        cart.setPrice(product.getUnitprice());
        cartService.addCart(cart);

        req.getRequestDispatcher("index.jsp").forward(req,resp);
    }
}
